package cn.kgc.listener.rabbitmq.chat;

import cn.hutool.json.JSONUtil;
import cn.kgc.base.BaseInfoProperties;
import cn.kgc.entity.ChatMsg;
import cn.kgc.listener.AbstractMessageListener;
import cn.kgc.mapper.ChatMsgMapper;
import cn.kgc.utils.RedisUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author YC
 */
@Component
public class ChatMessageListener extends AbstractMessageListener {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ChatMsgMapper chatMsgMapper;

    /**
     * 消费者从消息队列中拿取消息
     *
     * @param message 消息
     * @param channel 通道
     */
    @Override
    public void receiveMessage(Message message, Channel channel) {
        String jsonStr = new String(message.getBody());
        ChatMsg chatMsg = JSONUtil.toBean(jsonStr, ChatMsg.class);
        // 如果消息接收者不在线，需要统计信息（未读消息条数）
        if (!chatMsg.isReceiverOnline()) {
            String key = BaseInfoProperties.REDIS_UNREAD_MSG_COUNT + chatMsg.getReceiverId();
            long increment = redisUtil.hIncrement(key, chatMsg.getSenderId(), 1);
            // 未读消息统计保留一个月
            if (increment == 1) {
                redisUtil.expire(key, 31, TimeUnit.DAYS);
            }
        }
        // 无论消息的接收者是否在线，都要持久化
        chatMsgMapper.insert(chatMsg);
    }

}
